/*
 * Copyright (c) 2018. J4dream created
 */

package com.j4dream.property.javabasic.proxy;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Slf4j
public class CustomizeProxy implements InvocationHandler {

    private Object target;

    public CustomizeProxy(Class c) {
        try {
            this.target = c.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object result = method.invoke(target, args);
        after();
        log.info("proxy class:" + proxy.getClass());
        return result;
    }

    public void before() {
        log.info(this.getClass().getName() + "before call");
    }

    public void after() {
        log.info(this.getClass().getName() + "after call");
    }


    // 动态代理有别于静态代理，是根据代理的对象，动态创建代理类。这样，就可以避免静态代理中代理类接口过多的问题。动态代理是实现方式，
    // 是通过反射来实现的，借助Java自带的java.lang.reflect.Proxy,通过固定的规则生成。
    public static void main(String [] s){
        CustomizeProxy handle = new CustomizeProxy(ProxyImpl.class) ;
        ProxyInterface proxyImpl = (ProxyInterface) Proxy.newProxyInstance(CustomizeProxy.class.getClassLoader(), new Class[]{ProxyInterface.class}, handle);
        proxyImpl.doSomething();
    }
}
